<template>
  <div class="cart-page">
    <!-- 顶部导航栏 -->
    <Navbar />

    <div class="container">
      <!-- 面包屑 -->
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>购物车</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="cart-content">
        <!-- 购物车为空 -->
        <el-empty 
          v-if="!loading && cartList.length === 0" 
          description="购物车是空的"
          :image-size="200"
        >
          <el-button type="primary" @click="goToHome">去逛逛</el-button>
        </el-empty>

        <!-- 购物车列表 -->
        <div v-else v-loading="loading" class="cart-list">
          <!-- 全选栏 -->
          <div class="cart-header">
            <el-checkbox 
              v-model="allChecked" 
              :indeterminate="isIndeterminate"
              @change="handleCheckAll"
            >
              全选
            </el-checkbox>
            <span class="header-label">商品信息</span>
            <span class="header-label">单价</span>
            <span class="header-label">数量</span>
            <span class="header-label">小计</span>
            <span class="header-label">操作</span>
          </div>

          <!-- 商品列表 -->
          <div class="cart-items">
            <div 
              v-for="item in cartList" 
              :key="item.cartId"
              class="cart-item"
            >
              <el-checkbox v-model="item.checked" @change="handleCheckItem" />
              
              <div class="item-info" @click="goToDetail(item.goodsId)">
                <img :src="getImageUrl(item.picture)" class="item-image" />
                <div class="item-detail">
                  <h3 class="item-name">{{ item.goodsName }}</h3>
                  <p class="item-desc">{{ item.desc }}</p>
                </div>
              </div>

              <div class="item-price">¥{{ item.price }}</div>

              <div class="item-quantity">
                <el-input-number
                  v-model="item.goodsNum"
                  :min="1"
                  :max="999"
                  @change="handleQuantityChange(item)"
                />
              </div>

              <div class="item-subtotal">¥{{ (item.price * item.goodsNum).toFixed(2) }}</div>

              <div class="item-actions">
                <el-button 
                  type="danger" 
                  text 
                  :icon="Delete"
                  @click="handleDelete([item.goodsId])"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>

          <!-- 底部结算栏 -->
          <div class="cart-footer">
            <div class="footer-left">
              <el-checkbox 
                v-model="allChecked"
                :indeterminate="isIndeterminate"
                @change="handleCheckAll"
              >
                全选
              </el-checkbox>
              <el-button 
                text 
                type="danger"
                :disabled="checkedCount === 0"
                @click="handleDeleteChecked"
              >
                删除选中商品
              </el-button>
            </div>

            <div class="footer-right">
              <div class="total-info">
                <span>已选商品 <em>{{ checkedCount }}</em> 件</span>
                <div class="total-price">
                  <span>合计：</span>
                  <em>¥{{ totalPrice }}</em>
                </div>
              </div>
              <el-button 
                type="danger" 
                size="large"
                :disabled="checkedCount === 0"
                @click="handleCheckout"
              >
                结算
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getCartList, addOrRemoveGoods, deleteCartGoods } from '@/api/cart'
import { getFileUrl } from '@/api/file'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import Navbar from '@/components/Navbar.vue'

const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const cartList = ref([])

// 加载购物车列表
const loadCartList = async () => {
  loading.value = true
  try {
    const data = await getCartList()
    // 为每个商品添加选中状态
    cartList.value = (data || []).map(item => ({
      ...item,
      checked: false
    }))
  } catch (error) {
    console.error('获取购物车失败:', error)
  } finally {
    loading.value = false
  }
}

// 全选状态
const allChecked = computed({
  get: () => cartList.value.length > 0 && cartList.value.every(item => item.checked),
  set: (val) => {
    cartList.value.forEach(item => {
      item.checked = val
    })
  }
})

// 半选状态
const isIndeterminate = computed(() => {
  const checkedItems = cartList.value.filter(item => item.checked)
  return checkedItems.length > 0 && checkedItems.length < cartList.value.length
})

// 选中数量
const checkedCount = computed(() => {
  return cartList.value.filter(item => item.checked).length
})

// 总价
const totalPrice = computed(() => {
  const total = cartList.value
    .filter(item => item.checked)
    .reduce((sum, item) => sum + item.price * item.goodsNum, 0)
  return total.toFixed(2)
})

// 全选/取消全选
const handleCheckAll = (val) => {
  // 这里可以调用后端接口同步全选状态
  // await updateAllCheckStatus(val)
}

// 单选
const handleCheckItem = () => {
  // 可以在这里处理单选逻辑
}

// 数量变化
const handleQuantityChange = async (item) => {
  try {
    // 计算数量差
    const oldNum = item.goodsNum
    // 这里简化处理，实际应该记录原始数量
    // 可以调用添加/移除接口来更新数量
    console.log('数量变化:', item.goodsId, item.goodsNum)
  } catch (error) {
    console.error('更新数量失败:', error)
    ElMessage.error('更新数量失败')
    // 恢复原数量
    loadCartList()
  }
}

// 删除商品
const handleDelete = async (goodsIds) => {
  try {
    await ElMessageBox.confirm('确定要删除这些商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteCartGoods(goodsIds)
    ElMessage.success('删除成功')
    loadCartList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

// 删除选中商品
const handleDeleteChecked = () => {
  const goodsIds = cartList.value
    .filter(item => item.checked)
    .map(item => item.goodsId)
  
  if (goodsIds.length === 0) {
    ElMessage.warning('请先选择要删除的商品')
    return
  }

  handleDelete(goodsIds)
}

// 结算
const handleCheckout = () => {
  if (checkedCount.value === 0) {
    ElMessage.warning('请先选择要结算的商品')
    return
  }

  // 获取选中的商品ID和数量
  const selectedItems = cartList.value
    .filter(item => item.checked)
    .map(item => ({
      goodsId: item.goodsId,
      goodsNum: item.goodsNum
    }))

  // 跳转到订单确认页，通过 query 传递数据
  router.push({
    path: '/order-confirm',
    query: {
      from: 'cart',
      items: JSON.stringify(selectedItems)
    }
  })
}

// 获取图片URL
const getImageUrl = (imagePath) => {
  return getFileUrl(imagePath)
}

// 跳转到商品详情
const goToDetail = (goodsId) => {
  router.push(`/goods/${goodsId}`)
}

// 回到首页
const goToHome = () => {
  router.push('/')
}

onMounted(() => {
  // 检查是否登录
  if (!userStore.isLoggedIn()) {
    ElMessage.warning('请先登录')
    router.push('/')
    return
  }
  loadCartList()
})
</script>

<style scoped>
.cart-page {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  margin: 0;
  padding: 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
  padding-top: 20px;
}

.cart-content {
  min-height: 500px;
}

.cart-list {
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

/* 表头 */
.cart-header {
  display: grid;
  grid-template-columns: 50px 1fr 120px 150px 120px 100px;
  align-items: center;
  gap: 20px;
  padding: 20px;
  background: #f5f5f5;
  border-bottom: 1px solid #e8e8e8;
}

.header-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

/* 商品列表 */
.cart-items {
  padding: 0;
}

.cart-item {
  display: grid;
  grid-template-columns: 50px 1fr 120px 150px 120px 100px;
  align-items: center;
  gap: 20px;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.3s;
}

.cart-item:hover {
  background-color: #fafafa;
}

.item-info {
  display: flex;
  gap: 15px;
  cursor: pointer;
}

.item-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
}

.item-detail {
  flex: 1;
}

.item-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin: 0 0 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.item-desc {
  font-size: 12px;
  color: #999;
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-price {
  font-size: 16px;
  color: #ff4d4f;
  font-weight: 500;
}

.item-quantity {
  display: flex;
  justify-content: center;
}

.item-subtotal {
  font-size: 18px;
  color: #ff4d4f;
  font-weight: bold;
}

.item-actions {
  text-align: center;
}

/* 底部结算栏 */
.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-top: 2px solid #e8e8e8;
  background: #fafafa;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.footer-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.total-info {
  text-align: right;
}

.total-info span {
  font-size: 14px;
  color: #666;
  margin-right: 20px;
}

.total-info em {
  font-style: normal;
  color: #ff4d4f;
  font-weight: bold;
}

.total-price {
  margin-top: 5px;
}

.total-price span {
  font-size: 14px;
  color: #333;
}

.total-price em {
  font-size: 24px;
  color: #ff4d4f;
  font-weight: bold;
  margin-left: 5px;
}

@media (max-width: 768px) {
  .cart-header,
  .cart-item {
    grid-template-columns: 30px 1fr;
    gap: 10px;
  }

  .header-label {
    display: none;
  }

  .item-price,
  .item-quantity,
  .item-subtotal {
    grid-column: 2;
  }

  .item-actions {
    grid-column: 2;
  }

  .cart-footer {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }

  .footer-left,
  .footer-right {
    justify-content: space-between;
  }
}
</style>
